<?php

// +----------------------------------------------------------------------
// | 店铺处理
// +----------------------------------------------------------------------
// | Copyright (c) 2015-2024 http://www.yicmf.com, All rights reserved.
// +----------------------------------------------------------------------
// | Author: 微尘 <yicmf@qq.com>
// +----------------------------------------------------------------------

namespace app\event\im;

use app\common\event\Base;
use app\event\file\QrCode;
use app\model\im\Chat as ChatModel;
use app\model\store\StoreApp as StoreAppModel;
use app\pay\event\UserBalance as UserBalanceEvent;
use app\pay\model\Payment as PaymentModel;
use app\event\store\CommunityStoreModel;
use app\event\store\StoreCreditDeposit as StoreCreditDepositEvent;
use app\model\ucenter\User as UserModel;
use app\model\store\Store as StoreModel;
use app\event\ucenter\User as UserEvent;
use think\exception\HttpResponseException;
use think\facade\Cache;
use think\facade\Cookie;
use think\facade\Db;
use think\Exception;
use think\facade\Config;
use think\facade\Env;
use think\facade\Session;
use think\facade\Url;
use think\Response;

class Store extends Base
{

    public function getCustomer($request)
    {
        try {

            $track_id = $request->param('track_id', '');
            if ($track_id) {
                // 使用token访问
//                $re = UserEvent::getInfoByToken(think_decrypt($track_id, 'yicmf'), 'im');
                $data['data']['chat'] = ChatModel::where('sn|id', think_decrypt($track_id, 'yicmf'))->find();
                if ($data['data']['chat']) {
                    $re = UserEvent::loginById($data['data']['chat']['user_id'], 'im');
                    if ($re['code'] == 0) {
                        $data['data']['user'] = $re['data'];
                    }
                    $app = StoreAppModel::with('store')->where('id', $data['data']['chat']['store_app_id'])->find();

                } else {
                    throw new Exception('链接失效', 500);
                }
            }else{
                $app = StoreAppModel::with('store')->where('app_key', $request->param('app_key', $this->_getDefaultAppKey()))->find();
                if (!$app) {
                    throw new Exception('平台信息异常', 500);
                }
            }

            $customer = json_decode($request->param('customer', ''), true);
            $data['data']['store'] = $app['store'];
            $data['data']['app'] = $app;
            if (!isset($data['data']['user']) && cookie('customer_token')) {
                // 有上次缓存 访问
                $re = UserEvent::getInfoByToken(cookie('customer_token'), 'im');
                if ($re['code'] == 0) {
                    $data['data']['user'] = $re['data'];
                }
            } elseif (!empty($customer['customer_id'])) {
                // 指定id访问
                // 查询是否存在
                $user = UserModel::where('store_id', $data['data']['store']['id'])
                    ->where('type', 99)->where('customer_id',$customer['customer_id'])->find();
                if ($user) {
                    $re = UserEvent::loginById($user['id'], 'im');
                    if ($re['code'] == 0) {
                        $data['data']['user'] = $re['data'];
                    }
                }
            }
            if (!isset($data['data']['user'])) {
                // 注册用户信息
                $customer['store_id'] = $data['data']['store']['id'];
                $customer['store_app_id'] = $app['id'];
                $event = new UserEvent();
                $re = $event->register($customer, 'customer');
                if ($re['code'] == 0) {
                    $data['data']['user'] = $re['data'];
                } else {
                    throw new Exception($re['message'], 500);
                }
            }

            if ($request->action() == 'home') {
                //是否当前登录用户
//                if ($data['data']['user']['id'] != $data['data']['chat']['user_id']) {
//                    throw new Exception('非法链接', 500);
//                }
                $data['data']['service'] = UserModel::where('id', $data['data']['chat']['to_user_id'])->find();
            } elseif ($request->action() == 'init') {
                $customer = json_decode(cookie('customer_info'), true);
                if (cookie('customer_token') &&
                    (empty($customer['customer_id']) || (!empty($customer['customer_id']) && empty($customer['customer_id']) == cookie('customer_id'))
                    )) {
                    // 使用token访问
                    $re = UserEvent::getInfoByToken(cookie('customer_token'), 'im');
                    if ($re['code'] == 0) {
                        $data['data']['user'] = $re['data'];
                    }
                } elseif (!empty($customer['customer_id'])) {
                    // 指定id访问
                    // 查询是否存在
                    $user = UserModel::where('store_id', $data['data']['store']['id'])
                        ->where('type', 99)->where('customer_id', $request->param('customer_id', ''))->find();
                    if ($user) {
                        $re = UserEvent::loginById($user['id'], 'im');
                        if ($re['code'] == 0) {
                            $data['data']['user'] = $re['data'];
                        }
                    }
                }
                if (!isset($data['data']['user'])) {
                    // 注册用户信息
                    $customer['store_id'] = $data['data']['store']['id'];
                    $event = new UserEvent();
                    $re = $event->register($customer, 'customer');
                    if ($re['code'] == 0) {
                        $data['data']['user'] = $re['data'];
                    } else {
                        throw new Exception($re['message'], 500);
                    }
                }
            } elseif ($request->action() == 'start') {
            } else {
                if (cookie('customer_token')) {
                    // 使用token访问
                    $re = UserEvent::getInfoByToken(cookie('customer_token'), 'im');
                    if ($re['code'] == 0) {
                        $request->user = $re['data'];
                    }
                } else {
                    Cache::set('error_message', '访客注册信息异常');
                    $response = Response::create('/im/error/500', 'redirect', 500);
                    throw new HttpResponseException($response);
                }
            }

            if (isset($data['data']['user'])) {

                Cookie::forever('customer_token',  $data['data']['user']['token']['token']);
                //客服获取
//                $service_id = $request->param('service_id', Cookie::get('customer_service_id'));
//                if (!$service_id) {
////                    $service = UserModel::where('store_id', $store['id'])->where('is_open',1)->orderRaw('RAND()')->find();
//                    $service_id = UserModel::where('store_id', $store['id'])->where('is_open', 1)->where('type',1)->orderRaw('RAND()')->value('id');;
//                }
//                $re = UserEvent::getInfoById($service_id, 'im');
//                if ($re['code'] == 0) {
//                    $request->service = $re['data'];
//                    Cookie::forever('customer_service_id', $request->service['id']);
//                    Cookie::forever('customer_id', $request->user['id']);
//                    Cookie::forever('customer_token', $request->user['token']['token']);
//                } else {
//                    throw new Exception($re['message'], 500);
//                }
            }
//			dump($request->user);exit();
            $data['code'] = 0;
        } catch (\Exception $e) {
            $data['message'] = $e->getMessage();
            $data['code'] = 500;
        }
        return $data;
    }

    private function _getDefaultAppKey()
    {
        return Cookie::has('customer_store_app_key') ? Cookie::get('customer_store_app_key') : StoreAppModel::where('status', 1)->order('id ASC')->value('app_key');
    }

    /**
     * 当前店铺访问权限
     * @param StoreModel $store
     * @return mixed
     */
    public static function visitCheck($store)
    {
        try {
            if (1 != $store['is_open']) {
                throw new Exception('当前店铺已经关闭！');
            }
//				if (strtotime($store['end_time']) < time()) {
//					throw new Exception('当前店铺已经到期！');
//				}
//				$user = $store->user()->find();
            // 访问次数
//				$times = $store->visits()
//					->whereTime('create_time', 'today')
//					->where('status', '>', -2)->sum('times');
//				$grade = $store->grade()->find();
//				if ($times > $grade['visit_limit']) {
//					throw new Exception('当前店铺流量超限');
//				}

            // 佣金
//				$max_good_price = $store->goods()->where('status', 1)->where('is_on_sale', 1)->max('price') * $store['order_commission'];
//				if ($max_good_price > ($user['balance'] + $user['point'] / Config::get('store.point_to_balance') + $store['credit_deposit'])) {
//					throw new Exception('当前店铺异常关闭');
//				}
            $data['code'] = 0;
        } catch (Exception $e) {
            $data['code'] = 1;
            $data['message'] = $e->getMessage();
        }
        return $data;
    }

    /**
     * 访问店铺
     * @param           $param
     * @param StoreModel $store
     * @param           $tag
     * @return mixed
     */
    public static function visit($param, $store, $tag)
    {
        try {
            Db::startTrans();

            if ('home' == $tag) {
                // 访问首页
                $visit = $store->visits()
                    ->whereTime('create_time', 'today')
                    ->whereTime('create_time', '>', '-10 minute')
                    ->where('ip', request()->ip())
                    ->where('tag', 'home')
                    ->order('create_time DESC')
                    ->find();
                if (!$visit) {
                    $visit = [];
                    $visit['duration'] = 1;
                    $visit['from'] = 1;
                    $visit['times'] = 1;
                    $visit['tag'] = $tag;
                    $visit = $store->visits()->save($visit);
                } else {
//					if (strtotime($visit['update_time']) < time() - 1) {
//						$visit['duration'] = $visit['duration'] + 1;
//						$visit->save();
//					}
                }
            } else {
                $visit = $store->visits()
                    ->whereTime('create_time', 'today')
                    ->whereTime('create_time', '>', '-1 hour')
                    ->where('relation_id', $param['id'])
                    ->where('ip', request()->ip())
                    ->where('tag', 'good')
                    ->order('create_time DESC')
                    ->find();
                if (!$visit) {
                    $visit = [];
                    $visit['relation_id'] = $param['id'];
                    $visit['duration'] = 1;
                    $visit['from'] = 1;
                    $visit['times'] = 1;
                    $visit['tag'] = $tag;
                    $visit = $store->visits()->save($visit);
                } else {
//					if (strtotime($visit['update_time']) < time() - 1) {
//						$visit['duration'] = $visit['duration'] + 1;
//						$visit->save();
//					}
                }
            }

            Db::commit();

            $data['code'] = 0;
            $data['data'] = $visit->toArray();
        } catch (\Exception $e) {

            Db::rollback();
            $data['code'] = 1;
            $data['message'] = $e->getMessage();
        }
        return $data;
    }

    /**
     * 续费
     * @param           $param
     * @param UserModel $user
     * @return mixed
     */
    public function cost($param, $user)
    {
        try {
            $store = StoreModel::where('id', $param['id'])->find();
            if (!$store) {
                // 修改
                throw new Exception('店铺不存在');
            }
            if (!UserEvent::isAdministrator($user) && $store['user_id'] != $user['id']) {
                throw new Exception('没有权限');
            }
            Db::startTrans();
            $cost = [];
            $cost['start_time'] = strtotime($store['end_time']) > time() ? $store['end_time'] : time_format();
            if ($param['unit'] == 0) {
                // 续费月费
                $cost['title'] = '续费月费' . $param['number'] . '个月';
                $cost['price'] = $param['number'] * Config::get('store.month_fee');
                $cost['end_time'] = time_format(strtotime($cost['start_time']) + $param['number'] * 86400 * 31);
            } else {
                // 年费
                // 续费月费
                $cost['title'] = '续费年费' . $param['number'] . '年';
                $cost['price'] = $param['number'] * Config::get('store.year_fee');
                $cost['end_time'] = time_format(strtotime($cost['start_time']) + $param['number'] * 86400 * 31 * 12);
            }
            $store['end_time'] = $cost['end_time'];
            if (!$store->save()) {
                throw new Exception('续费时间异常');
            }
            $cost['admin_id'] = $user['id'];
            $cost['remark'] = $param['remark'];
            $cost['message'] = $param['message'];
            $store->costs()->save($cost);
            Db::commit();
            $data['code'] = 0;
            $data['message'] = '提交成功';
        } catch (Exception $e) {
            Db::rollback();
            $data['code'] = 1;
            $data['message'] = $e->getMessage();
        }
        return $data;
    }


    /**
     * 修改保证金
     * @param           $param
     * @param UserModel $user
     * @return mixed
     */
    public function credit($param, $user)
    {

        try {
            Db::startTrans();
            $store = StoreModel::where('id', $param['id'])->find();
            if (!$store) {
                throw new Exception('未查询到编辑的店铺');
            }

            if ($param['credit_deposit'] == $store['credit_deposit']) {
                throw new Exception('保证金无变更');
            } elseif ($param['credit_deposit'] < $store['credit_deposit']) {
                // 减少保证金
                $change = [];
                $change['relation_id'] = $user['id'];
                $change['amount'] = -($store['credit_deposit'] - $param['credit_deposit']);
                $change['change_code'] = 'admin_free_credit';
                $log = StoreCreditDepositEvent::change($change, $store);
                // 给店长充值
                $change = [];
                $change['relation_id'] = $log['id'];
                $change['amount'] = abs($store['credit_deposit'] - $param['credit_deposit']);
                $change['change_code'] = 'admin_free_credit';
                UserBalanceEvent::change($change, $store->user);
            } else {
                // 增加保证金
                $change = [];
                $change['relation_id'] = $user['id'];
                $change['amount'] = ($param['credit_deposit'] - $store['credit_deposit']);
                $change['change_code'] = 'admin_recharge_credit';
                StoreCreditDepositEvent::change($change, $store);
            }
            Db::commit();
            $data['code'] = 0;
            $data['message'] = '变更成功';
        } catch (\Exception $e) {

            Db::rollback();
            $data['code'] = 1;
            $data['message'] = $e->getMessage();
        }
        return $data;
    }


    /**
     * 生成二维码
     * @param StoreModel $store
     * @param bool $build
     * @return string
     * @author 微尘 <yicmf@qq.com>
     * @datetime: 2020/5/17 21:28
     */
    public static function buildStoreQrCode($store, $build = false)
    {
        $url = url('card/Store/index', ['code' => code_encode($store['id'])], true, true);
        $dir = 'store' . DIRECTORY_SEPARATOR . time_format($store['create_time'], 'Y/d') . DIRECTORY_SEPARATOR;
        $filename = $store['id'] . '.png';
        if (IS_SAFE_MODE) {
            $file = app()->getRootPath() . 'public' . DIRECTORY_SEPARATOR . 'uploads' . DIRECTORY_SEPARATOR . 'qrcode' . DIRECTORY_SEPARATOR . $dir;
        } else {
            $file = app()->getRootPath() . 'uploads' . DIRECTORY_SEPARATOR . 'qrcode' . DIRECTORY_SEPARATOR . $dir;
        }
        if (!is_file($file . $filename) || $build) {
            QrCode::build($url, $filename, $dir);
        }
        return '/uploads/qrcode/' . $dir . $filename;
    }


    /**
     * 初始化店铺信息
     * @param UserModel $user
     * @param $auth
     * @return StoreModel
     */
    public static function initInfo(UserModel $user, $auth): StoreModel
    {
        $store = [];
        $store['nickname'] = $auth['store_nickname'];
        $store['qq'] = $user['qq'];
        $store['user_id'] = $user['id'];
        $store['avatar_id'] = $user['avatar_id'];
        $store['mobile'] = $auth['store_mobile'];
        $store['contacts'] = $auth['store_contacts'];
        $store['order_commission'] = Config::get('store.order_commission');
        $store['end_time'] = time_format();
        $store['store_sn'] = self::_getStoreSn();
        $store['short_code'] = code_encode(self::_getStoreSn());
        $store = StoreModel::create($store);
        // 分类
        $insert = [
            'name' => '默认分类',
            'sort' => 100
        ];
        $store->categories()->save($insert);
        /// 默认线上支付宝开通
        $store->payments()->save(12);
        /// 默认规格
        $store->skus()->save(['name' => '颜色']);
        // 续费以及保证金
        $cost = [];
        $cost['start_time'] = strtotime($store['end_time']) > time() ? $store['end_time'] : time_format();
        // 续费月费
        $cost['title'] = '2022新入驻赠送' . Config::get('store.free_day') . '天';
        $cost['price'] = 0;
        $cost['admin_id'] = Config::get('ucenter.system_notice_from_user_id');
        $cost['end_time'] = time_format(Config::get('store.free_day') . ' days');
        $store->costs()->save($cost);
        $store['end_time'] = $cost['end_time'];
        $store->save();
        return $store;
        // 统计业务员信息
//			$salesman = $store->salesman()->find();

    }


    protected static function _getStoreSn()
    {
        return (StoreModel::max('store_sn') ?: 0) + 1;
    }

    /**
     * 审核社区经营
     * @param           $param
     * @param UserModel $admin
     * @return mixed
     */
    public function examine($param, $admin)
    {
        try {
            if (!$admin) {
                throw new Exception('管理不存在');
            }
            // 审核通过
            $store = CommunityStoreModel::where('id', $param['id'])->find();
            if (1 == $param['is_pass']) {
                $store['is_pass'] = 1;
            } else {
                $store['is_pass'] = -1;
                $store['refuse'] = $param['refuse'];
            }
            $store->save();
            $data['code'] = 0;
            $data['message'] = '提交成功';
        } catch (\Exception $e) {
            $data['code'] = 1;
            $data['message'] = $e->getMessage();
        }
        return $data;
    }

    /**
     * 审核社区经营
     * @param           $param
     * @param StoreModel $store
     * @return mixed
     */
    public function profile($param, $store)
    {
        try {
            $store['nickname'] = $param['nickname'];
            $store['mobile'] = $param['mobile'];
//				$store['qq'] = $param['qq'];
//				$store['wechat'] = $param['wechat'];
//				$store['announcement'] = $param['announcement'];
//				$store['website'] = $param['website'];
            $store['is_open'] = $param['is_open'];
            $store->save();
            $data['code'] = 0;
            $data['message'] = '资料修改成功';
        } catch (\Exception $e) {
            $data['code'] = 1;
            $data['message'] = $e->getMessage();
        }
        return $data;
    }


}
